package com.ubhave.powertracker;

import java.util.ArrayList;
import java.util.Date;

import com.ubhave.powertracker.R;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DiaryActivity extends FragmentActivity implements LoginDialogListener{
    
	Bundle bundle;
	Resources res;
	String date;
	String title;
	String name;
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	LifeGuideConnector lgc;
	
	PageSensorLogger psl;
	PageLogger pl;
	
	String activityPlan;
	String intro;
	
	String usr;
	String intervention;
	
	String[] sections;
	ArrayList<EditText> textBoxs;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);    	
    	
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.diary);
        
        settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        editor = settings.edit();
        res = getResources();
        lgc = new LifeGuideConnector(settings);
        bundle = getIntent().getExtras();
        
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
				
		if(bundle.getString("date")==null){
        	Date tempDate = new Date();
        	date=tempDate.getDate()+"-"+(tempDate.getMonth()+1)+"-"+(tempDate.getYear()+1900);
        }
        else
        	date = bundle.getString("date");
        
        title = bundle.getString("title");
        name = bundle.getString("name");
		
		activityPlan = settings.getString("PAplan", "");
		
		if(settings.getBoolean("SensorsOn", false))    		
			psl = new PageSensorLogger(this);
		pl = new PageLogger(this, name);
				
		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
		
				//Usage Logging
				/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+"("+name+") "+new Date()+", ");
        		editor.commit();
        		if(!usr.equals("")&&!intervention.equals(""))
        			lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
        		else
        			Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
				try{
					pl.makeLog();
        
        			//Sensor Logging
        			if(settings.getBoolean("SensorsOn", false)){
						psl.makeLog();
        			}
        		
        			String planValue = lgc.getVar(intervention, usr, "user", "PAplan",settings.getString("authkey",""));
        			if(planValue!=null){
        				editor.putString("PAplan", planValue);
        				editor.commit();
        				activityPlan = planValue;
        			}
        		
        			for(int i = 0; i<sections.length;i++){
        				String currentValue = lgc.getVar(intervention, usr, "user", name+"Diary-"+sections[i]+"-"+date,settings.getString("authkey",""));
        				if(currentValue!=null){
        					editor.putString(name+"Diary-"+sections[i]+"-"+date, currentValue);
        					editor.commit();
        					Log.i("POWeR Tracker Special: ", name+"Diary-"+sections[i]+"-"+date+" "+currentValue);
        				}
        			}
				} catch (PowerTrackerInvalidAuthKeyException e) {
					invalidKey();
				}
        		
                
        		
        		return null;
			}
			
			protected void onPostExecute(Object result) {
				setTitle();
				updateSections();
		    }
			
		};
		new AsyncLogAndRetrieve().execute(this);
        
        
        TextView titletv = (TextView)findViewById(R.id.DiaryTitle);
        titletv.setText(title);
        if(name.equals("activity")){
        	TextView introtv = (TextView)findViewById(R.id.DiaryIntro);
        	introtv.setText(res.getString(R.string.activity_diary_intro));
        }
        else if(name.equals("walking")){
        	TextView introtv = (TextView)findViewById(R.id.DiaryIntro);
        	introtv.setText(res.getString(R.string.walking_diary_intro));
        }
        
        setTitle();
        
        TextView datetv = (TextView)findViewById(R.id.DiaryCurrentDate);
        datetv.setText(date);
        
        textBoxs = new ArrayList<EditText>();
        sections = res.getStringArray(res.getIdentifier("diary_"+name+"_sections","array",getPackageName()));
        
        LinearLayout llmain = (LinearLayout)findViewById(R.id.DiaryLL);
        
        for(int i = 0; i<sections.length;i++){
        	TextView sectionHeader = new TextView(this);
        	sectionHeader.setText(sections[i]);
        	llmain.addView(sectionHeader);
        	
        	EditText textBox = new EditText(this);
        	textBox.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        	textBox.setSingleLine(false);
        	textBox.setGravity(Gravity.TOP);
        	        	
        	String currentValue = settings.getString(name+"Diary-"+sections[i]+"-"+date, "");
        	if(currentValue!=null)
        		textBox.setText(currentValue);
        	
        	llmain.addView(textBox);
                	
        	textBoxs.add(textBox);
        	
        }
        
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void diaryBack(View v){
    	
    	Intent myIntent = new Intent().setClass(this, DiaryActivity.class);
    	myIntent.putExtra("title", title);
    	myIntent.putExtra("name", name);
    	String[] datearr = date.split("-");
    	Date currDate = new Date(new Integer(datearr[2]),new Integer(datearr[1])-1,new Integer(datearr[0]));
    	long millidate = currDate.getTime();
    	Date newDate = new Date(millidate-(1000*60*60*24));
    	myIntent.putExtra("date", newDate.getDate()+"-"+(newDate.getMonth()+1)+"-"+newDate.getYear());
        startActivityForResult(myIntent, 0);
    	
    }
    
    public void diaryForward(View v){
    	
    	Intent myIntent = new Intent().setClass(this, DiaryActivity.class);
    	myIntent.putExtra("title", title);
    	myIntent.putExtra("name", name);
    	String[] datearr = date.split("-");
    	Date currDate = new Date(new Integer(datearr[2]),new Integer(datearr[1])-1,new Integer(datearr[0]));
    	long millidate = currDate.getTime();
    	Date newDate = new Date(millidate+(1000*60*60*24));
    	myIntent.putExtra("date", newDate.getDate()+"-"+(newDate.getMonth()+1)+"-"+newDate.getYear());
        startActivityForResult(myIntent, 0);
    	
    }

    public void submit(View v){
    	
    	class AsyncPost extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				try{
					for(int i = 0; i<textBoxs.size();i++){
						lgc.postVar(intervention, usr, "user", name+"Diary-"+sections[i]+"-"+date, textBoxs.get(i).getText().toString(),settings.getString("authkey",""));
						editor.putString(name+"Diary-"+sections[i]+"-"+date, textBoxs.get(i).getText().toString());
						editor.commit();
					}
				} catch (PowerTrackerInvalidAuthKeyException e) {
					invalidKey();
				}
				return null;
			}	
    	};
    	
    	//Use NI to check for a connection
    	ConnectivityManager cm = (ConnectivityManager)PowerTrackerApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if(ni!=null){
    	   	Toast.makeText(this, "Your diary entry has been saved", Toast.LENGTH_SHORT).show();
    	   	new AsyncPost().execute(this);
		}
		else {
			Toast.makeText(this, "You have no network connection. Please establish an internet connection before saving your diary.", Toast.LENGTH_SHORT).show();
		}
    }
    
    public void updateSections(){
    	for(int i = 0; i<sections.length;i++){
    		textBoxs.get(i).setText(settings.getString(name+"Diary-"+sections[i]+"-"+date, ""));
    		
    		//Log.i("POWeR Tracker Special: ", name+"Diary-"+sections[i]+"-"+date+" "+settings.getString(name+"Diary-"+sections[i]+"-"+date, ""));
    	}   	
    }
    
    public void setTitle(){
    	if(activityPlan.equals("walk")&&name.equals("activity")){
        	title="Walking Diary";
        }
    	 TextView titletv = (TextView)findViewById(R.id.DiaryTitle);
         titletv.setText(title);
    }
    
    public void invalidKey(){
		DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    dialog.show(this.getSupportFragmentManager(), "LoginDialog");
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}
    
}